﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using ZPod.MTG.Communication.Web;

namespace ZPod.MTG.Communication.Web
{
	/// <summary>
	/// Cliente basado en WCF por HTTP
	/// ConnectionString: Machine|Port|Name
	/// </summary>
	public class Client : BaseClient
	{
		IGameServerService _proxy;

		private IGameServerService Proxy
		{
			get
			{
				if (_proxy == null)
				{
					throw new NotConnectedException();
				}

				return _proxy;
			}
		}

		public override List<string> AvailableGames
		{
			get
			{
				return Proxy.GetAvailableGames();
			}
		}

		public override GameState CurrentState
		{
			get
			{
				return Proxy.GetGame(CurrentGame);
			}
		}

		public override void CreateGame(string name)
		{
			Proxy.CreateGame(name);
		}

		public override void SetPlayerState(PlayerState state)
		{
			Proxy.SetState(CurrentGame, PlayerName, state);
		}

		public override void Connect()
		{
			if (_proxy != null)
			{
				var parts = ConnectionString.Split('|');
				var address = String.Format("http://{0}:{1}{2}", parts[0], parts[1], parts[2]);

				_proxy = ServiceClient<IGameServerService>.CreateServiceChannel(
					"MTGServerEndpoint",
					address);
			}
		}

		public override void Disconnect()
		{
			ServiceClient<IGameServerService>.DisposeProxy(Proxy);
			_proxy = null;
		}

		public override void Dispose()
		{
			if (_proxy != null)
			{
				Disconnect();
			}
		}

		public override void AddCommonCard(Card card)
		{
			Proxy.AddCommonCard(CurrentGame, card);
		}

		public override void RemoveCommonCard(int index)
		{
			Proxy.RemoveCommonCard(CurrentGame, index);
		}
	}
}
